#include "myopenglwindow.h"
#include <QPainter>

MyOpenGLWindow::MyOpenGLWindow(QWindow *parent)
    : QWindow (parent)
{
    setSurfaceType( QWindow::OpenGLSurface );
}

void MyOpenGLWindow::render( QPainter *painter ) {
    Q_UNUSED( painter );
}

void MyOpenGLWindow::initialize() {

}

void MyOpenGLWindow::render() {
    if( !m_device ) {
        m_device = new QOpenGLPaintDevice;
    }

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    m_device->setSize( size() * devicePixelRatio() );
    m_device->setDevicePixelRatio( devicePixelRatio() );

    QPainter painter( m_device );
    render( &painter );
}

void MyOpenGLWindow::renderLater(){
    requestUpdate();
}

bool MyOpenGLWindow::event( QEvent *e ) {
    switch ( e->type() ) {
    case QEvent::UpdateRequest :
        renderNow();
        return true;
        break;
    default:
        return QWindow::event(e);
        break;
    }
}

void MyOpenGLWindow::exposeEvent( QExposeEvent *e ) {
    Q_UNUSED( e );
    if ( isExposed() ) {
        renderNow();
    }
}

void MyOpenGLWindow::renderNow() {
    if( !isExposed() )
        return;

    bool needInitialize = false;

    if( !m_context ) {
        m_context = new QOpenGLContext( this );
        m_context->setFormat( requestedFormat() );
        m_context->create();
        needInitialize = true;
    }

    m_context->makeCurrent(this);

    if (needInitialize) {
        initializeOpenGLFunctions();
        initialize();
    }

    render();

    m_context->swapBuffers(this);

    if ( m_animating ) {
        renderLater();
    }

}

void MyOpenGLWindow::setAnimating( bool animating ) {
    m_animating = animating;

    if ( animating ) {
        renderLater();
    }
}


